const util = require('../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    /* 1：报名-路线调整，2：报名-确认行程，3：报名-班次实施，4：报名-我要反馈，5：派单-接受订单，6：派单-路线调整，7：派单-组织派单，8：派单-过程管理，9：结果反馈 */
    type: '',
    tabIndex: 0,
    tabList: [
      {
        list: [],
        name: '全部',
        pageNo: 1,
        pageSize: 15,
        totalPage: 1,
        loading: false,
        end: false,
        value: '',
        scrollTop: 0
      }
    ],
    keyword: '',
    showClear: false
  },
  //派单
  paidan(e) {
    const {item} = e.currentTarget.dataset;
    const { pdgl_order_id, pdgl_pk_billtype, pdgl_process_id, pdgl_pk,pdgl_task_id } = item;
    util.request(util.API_BASE_APP_URL+'itf/common/hongpei/getToken.json', {
      'X-EOA-TOKEN': wx.getStorageSync('X-EOA-TOKEN') || ''
    }).then(res => {
      if (res.success) {
        let url = `/pages/pdWebView/pdWebView`;
        url += `?orderId=${pdgl_order_id}`;
        url += `&taskId=${pdgl_task_id}`;
        url += `&processId=${pdgl_process_id}`;
        url += `&pk_billtype=${pdgl_pk_billtype}`;
        url += `&billid=${pdgl_pk}`;
        url += `&X-EOA-TOKEN=${res.data}`;
        wx.navigateTo({
          url,
        })
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //下载PDF
  downloadPDF(e) {
    const _this = this;
    const { billid } = e.currentTarget.dataset;
    util.request('itf/common/hongpei/travelorder/getPdf.json', {
      billid
    }).then(res => {
      if (res.success) {
        // 显示加载提示
        wx.showLoading({ title: '下载中...' });

        // PDF 文件的远程地址（需配置合法域名）
        const fileUrl = util.API_BASE_URL + util.removeLeadingSlash(res.data);

        // 下载文件到临时路径
        wx.downloadFile({
          url: fileUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              // 下载成功，打开文档预览
              wx.openDocument({
                filePath: res.tempFilePath,
                showMenu: true,
                fileType: 'pdf',
                success: (res) => {
                  // 提示用户通过右上角菜单保存
                  // wx.showToast({ title: '已打开，请保存', icon: 'none' });
                },
                fail: (err) => {
                  util.showMsg({
                    msg: '打开失败',
                    icon: 'error'
                  })
                }
              });
            }
          },
          fail: (err) => {
            util.showMsg({
              msg: '下载失败',
              icon: 'error'
            })
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //评价
  comment(e) {
    const { billid } = e.currentTarget.dataset;
    const { type } = this.data;
    wx.navigateTo({
      url: '/pages/comment/comment?billid=' + billid + '&type=' + type,
    })
  },
  //路线调整
  luxiantiaozheng(e) {
    const billid = e.currentTarget.dataset.billid;
    const { type } = this.data;
    wx.navigateTo({
      url: '/pagesTripbill/routeCorrect/routeCorrect?billid=' + billid + '&type=' + type,
    })
  },
  //接单
  takeOrder(e) {
    const _this = this;
    const billid = e.currentTarget.dataset.billid;
    wx.showModal({
      title: '提示',
      content: '是否确认接单？',
      success(res) {
        if (res.confirm) {
          util.request('/itf/common/hongpei/travelorder/receive.json', {
            billid
          }, "POST").then(res => {
            if (res.success) {
              util.showMsg({
                msg: "接单成功",
                icon: 'success',
                success: () => {
                  _this.refresh();
                }
              });
            } else {
              util.showMsg({ msg: res.message || res.msg });
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //删除
  delete(e) {
    const _this = this;
    const billid = e.currentTarget.dataset.billid;
    let billidList = [billid]
    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success(res) {
        if (res.confirm) {
          util.request('/itf/common/hongpei/travelorder/delete.json', {
            billidList
          }, "POST").then(res => {
            if (res.success) {
              util.showMsg({
                msg: "删除成功",
                icon: 'success',
                success: () => {
                  _this.refresh();
                }
              });
            } else {
              util.showMsg({ msg: res.message || res.msg });
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //前往行程单预览页面
  goTripPreview(e) {
    const billid = e.currentTarget.dataset.billid;
    const type = this.data.type;
    wx.navigateTo({
      url: '/pagesTripbill/tripPreview/tripPreview?billid=' + billid + '&type=' + type,
    })
  },
  //刷新
  refresh() {
    const tabIndex = this.data.tabIndex;
    this.setData({
      [`tabList[${tabIndex}].pageNo`]: 1,
      [`tabList[${tabIndex}].totalPage`]: 1
    })
    this.getListData()
  },
  //关键字搜索
  onSearch() {
    this.refresh();
  },
  onInput(e) {
    const value = e.detail.value;
    this.setData({
      showClear: value !== ''
    });
  },
  clearInput() {
    this.setData({
      keyword: '',
      showClear: false
    });
  },
  changeTab(e) {
    const tabIndex = e.currentTarget.dataset.index;
    if (this.data.tabIndex != tabIndex) {
      this.setData({
        tabIndex
      })
    } else {
      //如果相同页签就刷新
      this.refresh();
    }
  },
  //swiper切换
  changeSwiper(e) {
    this.setData({
      tabIndex: e.detail.current
    })
  },
  //视口滚动到底部触发
  lower() {
    let tabIndex = this.data.tabIndex;
    let { end, loading } = this.data.tabList[tabIndex];
    //如果还没到最后一页，就继续请求
    if (!end && !loading) {
      this.getListData();
    }
  },
  //获取列表数据
  getListData() {
    const _this = this;
    let type = this.data.type;
    let tabIndex = this.data.tabIndex;
    let { pageNo, pageSize, loading } = this.data.tabList[tabIndex];
    this.setData({
      [`tabList[${tabIndex}].loading`]: true
    })
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    util.request('/itf/common/hongpei/travelorder/queryTravelOrderByPage.json', {
      keyword: _this.data.keyword,
      pageNo,
      pageSize,
      type
    }).then(res => {
      wx.hideLoading()
      _this.setData({
        [`tabList[${tabIndex}].loading`]: false
      })
      if (res.success) {
        let end = res.totalPage == _this.data.tabList[tabIndex].totalPage ? true : false;
        _this.setData({
          [`tabList[${tabIndex}].list`]: res.records,
          [`tabList[${tabIndex}].pageNo`]: pageNo++,
          [`tabList[${tabIndex}].totalPage`]: res.totalPage,
          [`tabList[${tabIndex}].end`]: end
        })
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let title = '';
    this.setData({ type: options.type })
    switch (Number(options.type)) {
      case 1:
        title = "路线调整";
        break;
      case 2:
        title = "确认行程";
        break;
      case 3:
        title = "班次实施";
        break;
      case 4:
        title = "我要反馈";
        break;
      case 5:
        title = "接受订单";
        break;
      case 6:
        title = "路线调整";
        break;
      case 7:
        title = "组织派单";
        break;
      case 8:
        title = "过程管理";
        break;
      case 9:
        title = "结果反馈";
        break;
    }
    if (title) {
      wx.setNavigationBarTitle({
        title
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getListData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})